﻿using NetMQ;
using NetMQ.Sockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NETMQLib
{
    public class ClientMQ
    {
        RequestSocket socket = null;
        public event Action<string> ReceiveFrameStringEvent;
        string url = "";

        public ClientMQ(string ip, int port)
        {
            try
            {
                url = $"tcp://{ip}:{port}";
                socket = new RequestSocket();
                socket.Connect(url);
                Task.Factory.StartNew(RecvString);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void SendData(string msg)
        {
            try
            {
                //如果释放了就重新new
                if (socket.IsDisposed)
                {
                    socket = new RequestSocket();
                    socket.Connect(url);
                }
                socket.SendFrame(msg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void RecvString()
        {
            while (true)
            {
                try
                {
                    string msg = socket.ReceiveFrameString(Encoding.UTF8);
                    if (msg == "exit")
                    {
                        break;
                    }
                    ReceiveFrameStringEvent?.Invoke(msg);
                }
                catch (Exception ex)
                {
                    if (socket.IsDisposed)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                    continue;
                }
            }
        }

        public void Dispose()
        {
            if (socket != null && !socket.IsDisposed)
            {
                socket.Unbind(url);
                socket.Close();
                socket.Dispose();
            }
        }
    }
}
